package com.fat.interceptors;

import com.fat.contains.ContainsStatus;
import com.fat.pojo.Result;
import com.fat.utils.JwtUtil;
import com.fat.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;


@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //拦截器拦截请求，判断是否登录
        String token = request.getHeader("Authorization");
        try {
            if(StringUtils.hasLength(token)){
                //解析Token
                Map<String, Object> map = JwtUtil.parseToken(token);
                //判断Token是否和Redis中的Token一致
                if(redisTemplate.hasKey(ContainsStatus.REDIS_USER_PREFIX+map.get("id"))){
                    //一致，刷新Token时间
                    redisTemplate.expire(token, 12, java.util.concurrent.TimeUnit.HOURS);
                }else{
                    response.setStatus(401);
                    return false;
                }
                //将用户信息存入ThreadLocal
                ThreadLocalUtil.set(map);
                return true;
            }else{
                response.setStatus(401);
                return false;
            }
        }catch (Exception e){
            response.setStatus(401);
            return false;
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //请求结束后，清除ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }
}
